<?php

class ContentController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actions() {
        return array(
            // captcha action renders the CAPTCHA image displayed on the contact page
            'captcha' => array(
                'class' => 'CaptchaExtendedAction',
            ),
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('captcha'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'addimage', 'addvideo', 'addcontent'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'view', 'approve'),
                'roles' => array('moderator'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions' => array('index', 'view', 'admin', 'delete', 'approve'),
                'roles' => array('admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Content;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Content'])) {
            $model->attributes = $_POST['Content'];
            if ($model->validate())
                $this->redirect(array('view', 'id' => $model->content_id));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionApprove($cid) {
        $content = new Content;
        $found = $content->findByAttributes(array('content_id' => $cid));
        $return = '';
        if ($found->is_approved == 1)
            $return = 'waiting';
        if ($found->is_approved == 0)
            $return = 'moderation';
        if ($found->is_approved < 2) {
            $found->is_approved = strval(intval($found->is_approved) + 1);
            $found->date_approved = new CDbExpression('NOW()');
            if ($found->save())
                Yii::app()->user->setFlash('success', "Materiał został zaakceptowany przez moderatora!");
            else
                Yii::app()->user->setFlash('error', "Błąd akceptacji materiału!");
        } else
            Yii::app()->user->setFlash('error', "Materiał jest już zaakceptowany!");

        $this->redirect(array('site/index', 'c' => $return));
    }

    public function actionAddcontent() {
        $model = new AddImageForm;
        $videomodel = new AddVideoForm;
        if (isset($_POST['AddImageForm'])) {
            $model->attributes = $_POST['AddImageForm'];
            $model->file = CUploadedFile::getInstance($model, 'file');
            if ($model->validate()) {
                fb::log($model->file, "Model");
                $content = new Content;
                $content->attributes = $_POST['AddImageForm'];
                $content->file = CUploadedFile::getInstance($model, 'file');
                $content->source = $model->source;
                $content->is_video = 0;
                $content->title = $model->title;
                $randname = $this->random_gen(10) . ".gif";
                $fullpath = YiiBase::getPathOfAlias('application') . '\\..\\images\\content\\' . $randname;
                $saveRes = $content->file->saveAs($fullpath);
                if ($saveRes) {
                    $ir = new ImageResize();
                    $ir->load($fullpath);
                    if ($ir->getWidth() > 600)
                        $ir->resizeToWidth(600);
                    //$saveResult = $content->file->saveAs($fullpath);
                    if ($ir->save($fullpath, $compression = 75))
                        $content->file = $randname;
                    if ($content->save()) {
                        Yii::app()->user->setFlash('success', "Dodany material zostal umieszczony w kolejce do moderacji!");
                        $this->redirect(array('/content/addcontent', 'id' => $content->content_id));
                    }
                } else {
                    Yii::app()->user->setFlash('error', "Problem podczas zapisu pliku!");
                    $this->redirect(array('/content/addcontent'));
                }
            }
        }
        if (isset($_POST['AddVideoForm'])) {
            fb::log($_POST['AddVideoForm']);
            $videomodel->attributes = $_POST['AddVideoForm'];
            if ($videomodel->validate()) {
                fb::log("Validated");
                $content = new Content;
                $content->attributes = $_POST['AddVideoForm'];
                $content->is_video = 1;
                $content->file = "";
                $content->title = $videomodel->title;
                //$converted = preg_replace('/.+(\?|&)v=([^\/&]+).*/', 'http://youtube.com/embed/$2', $videomodel->url);
                $converted = $this->linkifyYouTubeURLs($videomodel->url);
                $content->url = $converted;
                if ($content->save()) {
                    Yii::app()->user->setFlash('success', "Dodany material zostal umieszczony w kolejce do moderacji!");
                    $this->redirect(array('/content/addcontent', array('show' => 'video')));
                } else {
                    Yii::app()->user->setFlash('error', "Problem podczas zapisu pliku!");
                    $this->redirect(array('/content/addcontent', array('show' => 'video')));
                }
            } else {
                fb::log("Not Validated");
                fb::log($videomodel->getErrors());
            }
        }
        $params = array(
            'model' => $model,
            'videomodel' => $videomodel
        );
        if (isset($_POST['AddVideoForm']))
            $params['show'] = 'video';
        $this->render('addcontent', $params);
    }

    private function linkifyYouTubeURLs($text) {
        $text = preg_replace('~
        # Match non-linked youtube URL in the wild. (Rev:20111012)
        https?://         # Required scheme. Either http or https.
        (?:[0-9A-Z-]+\.)? # Optional subdomain.
        (?:               # Group host alternatives.
          youtu\.be/      # Either youtu.be,
        | youtube\.com    # or youtube.com followed by
          \S*             # Allow anything up to VIDEO_ID,
          [^\w\-\s]       # but char before ID is non-ID char.
        )                 # End host alternatives.
        ([\w\-]{11})      # $1: VIDEO_ID is exactly 11 chars.
        (?=[^\w\-]|$)     # Assert next char is non-ID or EOS.
        (?!               # Assert URL is not pre-linked.
          [?=&+%\w]*      # Allow URL (query) remainder.
          (?:             # Group pre-linked alternatives.
            [\'"][^<>]*>  # Either inside a start tag,
          | </a>          # or inside <a> element text contents.
          )               # End recognized pre-linked alts.
        )                 # End negative lookahead assertion.
        [?=&+%\w]*        # Consume any URL (query) remainder.
        ~ix', 'http://www.youtube.com/embed/$1', $text);
        return $text;
    }

    private function random_gen($length) {
        $random = "";
        srand((double) microtime() * 1000000);
        $char_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $char_list .= "abcdefghijklmnopqrstuvwxyz";
        $char_list .= "1234567890";
        // Add the special characters to $char_list if needed

        for ($i = 0; $i < $length; $i++) {
            $random .= substr($char_list, (rand() % (strlen($char_list))), 1);
        }
        return $random;
    }

    public function actionAddvideo() {
        
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if (isset($_POST['Content'])) {
            $model->attributes = $_POST['Content'];
            if ($model->save())
                $this->redirect(array('view', 'id' => $model->content_id));
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            $model = $this->loadModel($id);
            if ($model->file)
                if (unlink(Yii::app()->basePath . "\\..\\images\\content\\" . $model->file)) {
                    $this->loadModel($id)->delete();
                    Yii::app()->user->setFlash('success', "Materiał został poprawnie usunięty.");
                } else
                    Yii::app()->user->setFlash('error', "Błąd podczas usuwania materiału.");
            else {
                $this->loadModel($id)->delete();
                Yii::app()->user->setFlash('success', "Materiał został poprawnie usunięty.");
            }

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if (!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $dataProvider = new CActiveDataProvider(
                        'Content',
                        array(
                            'pagination' => array('pageSize' => Yii::app()->params['itemsPerPage']),
                            'criteria' => array(
                                'condition' => '(NOT url is NULL OR NOT file is NULL)',
                                'order' => 'content_id ASC'
                            )
                ));
        $title = 'Przegląd moderatora';
        $this->redirect(array('site/index', 'c' => 'moderation'));
    }

    /**
     * Manages all models.
     */
    public function actionAdmin() {
        $model = new Content('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Content']))
            $model->attributes = $_GET['Content'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Content::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'content-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

}
